/**
 * Copyright (c) [2022] [yanyeori]
 * [yanyeori-service] is licensed under Mulan PSL v2.
 * You can use this software according to the terms and conditions of the Mulan PSL v2.
 * You may obtain a copy of Mulan PSL v2 at: http://license.coscl.org.cn/MulanPSL2
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
 * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
 * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PSL v2 for more details.
 */
package com.yanyeori.service.file.business.service.impl;

import com.yanyeori.framework.core.util.FileUtil;
import com.yanyeori.service.file.api.dto.FileDTO;
import com.yanyeori.service.file.business.config.LocalConfig;
import com.yanyeori.service.file.business.exception.FileException;
import com.yanyeori.service.file.business.service.LocalFileService;
import com.yanyeori.service.file.business.util.FileServiceUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;

/**
 * 本地文件存储
 *
 * @author lotus
 */
@Service
public class LocalFileServiceImpl implements LocalFileService {
    private final Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    private LocalConfig localConfig;

    /**
     * 本地文件上传接口
     *
     * @param file 上传的文件
     * @return 文件上传信息
     */
    @Override
    public FileDTO upload(MultipartFile file) throws IOException {
        String fileName = file.getOriginalFilename();
        String filePath = FileServiceUtil.extractFilePath(fileName);
        FileUtil.writeFromStream(file.getInputStream(), localConfig.getPath() + "/" + filePath);
        logger.info("file[{}] upload to LOCAL success", fileName);
        String url = localConfig.getDomain() + localConfig.getPrefix() + "/" + filePath;
        return new FileDTO(fileName, filePath, url);
    }

    /**
     * 本地文件下载接口
     *
     * @param filePath 文件路径
     */
    @Override
    public void download(String filePath, HttpServletResponse response) throws IOException {
        String path = localConfig.getPath() + "/" + filePath;
        File file = new File(path);
        String fileName = FileUtil.getName(filePath);
        if (!file.exists()) {
            throw new FileException("file [{}] not exist", fileName);
        }
        response.setContentType("application/force-download");
        response.addHeader("Content-Disposition", "attachment;fileName=" + new String(fileName.getBytes("gb2312"), "ISO8859-1"));
        FileUtil.writeToStream(file, response.getOutputStream());
    }
}
